#include "autoclient.h"

#include <QJsonObject>
#include <QDebug>
#include <math.h>

#include "databasemagr.h"
#include "command.h"
#include "config.h"

QStringList AutoClient::m_chatMsgList = {"你好啊", "在干啥？", "你瞅啥？", "瞅你咋地",
    "走，出去浪", "不去，我爱学习", "C++真好玩儿!", "哎吆歪", "我要学习Reactor", "再见!"};

AutoClient::AutoClient(QObject *parent):
    QObject(parent)
{
    m_msgSocket = new MsgSocket(this);
}

void AutoClient::autoChatWithFriend(void)
{
    static QString fname;
    int count = m_friendList.m_userCount;
    if(count > 5)
    {
        fname = m_friendList.getUserNameList().at(rand()%count);
        userChatWithFriend(fname, m_chatMsgList.at(rand()%10));
    }
}

void AutoClient::connectToServer(const QString &host, const int &port)
{
    connect(m_msgSocket, SIGNAL(signalStatus(quint8)),
            this, SLOT(SltTcpStatus(quint8)));
    connect(m_msgSocket, SIGNAL(signalMessage(quint8,QJsonValue)),
            this, SLOT(SltTcpReply(quint8,QJsonValue)));
    m_msgSocket->ConnectToHost(host, port);
}

void AutoClient::userRegisterAskMsg(const QString &name, const QString &passwd)
{
    QJsonObject json;
    m_msgSocket->m_localUser.m_name = name;
    m_msgSocket->m_localUser.m_pswd = passwd;
    json.insert("name", name);
    json.insert("passwd", passwd);
    m_msgSocket->SltSendMessage(Register, json);
}

void AutoClient::userLoginAskMsg(const QString &name, const QString &passwd)
{
    QJsonObject json;
    json.insert("name", name);
    json.insert("passwd", passwd);
    m_msgSocket->m_localUser.m_name = name;
    m_msgSocket->SltSendMessage(Login, json);
}

void AutoClient::userGetFriendsAskMag(void)
{
    // 上线的时候获取当前好友的状态
    QJsonArray friendArr = DataBaseMagr::Instance()->GetMyFriend(m_msgSocket->m_localUser.m_id);

    // 组织Jsonarror
    m_msgSocket->SltSendMessage(GetMyFriends, friendArr);
}

void AutoClient::userAddFriendAskMsg(const QString &f_name)
{
    QJsonObject json;
    json.insert("id", m_msgSocket->m_localUser.m_id);
    json.insert("name", f_name);
    m_msgSocket->SltSendMessage(AddFriend, json);
}

void AutoClient::userChatWithFriend(const QString &name, const QString &text)
{
    QJsonObject json;
    json.insert("id", m_msgSocket->m_localUser.m_id);
    json.insert("to", m_friendList.getUserInfo(name).m_id);
    json.insert("msg", text);
    json.insert("type", Text);

    m_msgSocket->SltSendMessage(SendMsg, json);
}

/**
 * @brief MainWindow::SltTcpStatus
 * tcp状态监听
 * @param state
 */
void AutoClient::SltTcpStatus(const quint8 &state)
{
    switch (state) {
    case DisConnectedHost: {
        emit signalUserOffline(m_msgSocket->m_localUser);
    }
        break;
    case ConnectedHost:
    {
        QJsonObject json;
        json.insert("name", m_msgSocket->m_localUser.m_name);
        json.insert("passwd", m_msgSocket->m_localUser.m_pswd);
    }
        break;
    case LoginSuccess:
    {
        emit signalUserOnline(m_msgSocket->m_localUser);
        userGetFriendsAskMag();
    }
        break;
    case RegisterOk:
        userLoginAskMsg(m_msgSocket->m_localUser.m_name,
                        m_msgSocket->m_localUser.m_pswd);
    default:
        break;
    }
}

void AutoClient::SltTcpReply(const quint8 &type, const QJsonValue &dataVal)
{
    switch (type) {
    case UpdateHeadPic: ParseUpFriendHead(dataVal); break;
    case AddFriend: ParseAddFriendReply(dataVal); break;
    case AddFriendRequist: ParseAddFriendRequest(dataVal); break;

    case GetMyFriends: ParseGetFriendsReply(dataVal); break;
    case RefreshFriends: ParseRefreshFriendsReply(dataVal); break;

    case SendMsg: ParseFriendMessageReply(dataVal); break;
    case SendFile: ParseFriendMessageReply(dataVal); break;
    case SendPicture: ParseFriendMessageReply(dataVal); break;
    default:
        break;
    }
}


/**
 * @brief TcpClient::ParseAddFriendReply
 * @param message
 */
void AutoClient::ParseAddFriendReply(const QJsonValue &dataVal)
{
    if(dataVal.isObject())
    {
        QJsonObject dataObj = dataVal.toObject();

        int nStatus = dataObj.value("status").toInt();

        int nId = dataObj.value("id").toInt();
        // 未查询到该用户
        if (-1 == nId)
        {
            return;
        }

        UserInfo info;
        info.m_head = dataObj.value("head").toString();
        // 头像判断，如果不在就申请
        if (!QFile::exists(Config::m_strHeadPath + info.m_head))
        {
            QJsonObject jsonObj;
            jsonObj.insert("from", Config::m_nId);
            jsonObj.insert("id",  -2);
            jsonObj.insert("msg", info.m_head);
            m_msgSocket->SltSendMessage(GetFile, jsonObj);
        }

        info.m_name      = dataObj.value("name").toString();
        info.m_id        = nId;
        info.m_statu    = nStatus;

        m_friendList.appendUserInfo(info);
    }
}

/**
 * @brief AutoClient::ParseAddFriendRequest
 * 被别人添加为好友
 * @param dataVal
 */
void AutoClient::ParseAddFriendRequest(const QJsonValue &dataVal)
{
    if(dataVal.isObject())
    {
        UserInfo info;
        QJsonObject jsonObj = dataVal.toObject();
        info.m_id = jsonObj.value("id").toInt();
        info.m_name = jsonObj.value("name").toString();
        info.m_head = jsonObj.value("msg").toString();

        // 判断我是否已经添加该好友
        if(!DataBaseMagr::Instance()->isMyFriend(m_msgSocket->m_localUser.m_id, info.m_name))
        {
            info.m_head  = Config::m_strHeadPath + jsonObj.value("head").toString();
            info.m_statu    = OnLine;

            // 更新至数据库
            DataBaseMagr::Instance()->AddFriend(info.m_id, m_msgSocket->m_localUser.m_id, info.m_name);
        }

        m_friendList.appendUserInfo(info);
    }
}

/**
 * @brief AutoClient::ParseMyFriendsReply
 * @param dataVal
 */
void AutoClient::ParseGetFriendsReply(const QJsonValue &dataVal)
{
    // data 的 value 是数组
    if(dataVal.isArray())
    {
        QJsonArray array = dataVal.toArray();
        int nSize = array.size();
        for (int i = 0; i < nSize; ++i)
        {
            QJsonObject jsonObj = array.at(i).toObject();
            int nStatus = jsonObj.value("status").toInt();

            QString strHead = jsonObj.value("head").toString();

            // 头像判断，如果不在就申请
            if (!QFile::exists(Config::m_strHeadPath + strHead))
            {
                QJsonObject jsonObj;
                jsonObj.insert("from", m_msgSocket->m_localUser.m_id);
                jsonObj.insert("id",  -2);
                jsonObj.insert("msg", strHead);
                m_msgSocket->SltSendMessage(GetFile, jsonObj);
            }

            UserInfo info;
            info.m_head  = Config::m_strHeadPath + jsonObj.value("head").toString();
            info.m_name      = jsonObj.value("name").toString();
            info.m_id        = jsonObj.value("id").toInt();
            info.m_statu    = nStatus;

            m_friendList.appendUserInfo(info);
        }
    }

    // 上报我的上线消息
    m_msgSocket->SltSendOnline();
}

/**
 * @brief AutoClient::ParseRefreshFriendsReply
 * 刷新好友
 * @param dataVal
 */
void AutoClient::ParseRefreshFriendsReply(const QJsonValue &dataVal)
{
    qDebug() << "ParseRefreshFriendsReply: " << dataVal;
    // data 的 value 是数组
    if (dataVal.isArray()) {
        QJsonArray array = dataVal.toArray();
        int nSize = array.size();
        for (int i = 0; i < nSize; ++i) {
            QJsonObject jsonObj = array.at(i).toObject();
            int nId = jsonObj.value("id").toInt();
            int nStatus = jsonObj.value("status").toInt();
            QString strHead = jsonObj.value("head").toString();

//            QList<QQCell *> friends = ui->frindListWidget->getCells();
//            foreach (QQCell *cell, friends.at(0)->childs) {
//                if (cell->id == nId) {
//                    cell->SetSubtitle(strHead);
//                    cell->SetSubtitle(QString("当前用户状态：%1 ").arg(OnLine == nStatus ? tr("在线") : tr("离线")));
//                }
//            }

//            ui->frindListWidget->upload();
        }
    }
}

/**
 * @brief AutoClient::ParseMessageReply
 * @param dataVal
 */
void AutoClient::ParseFriendMessageReply(const QJsonValue &dataVal)
{
    if (dataVal.isObject())
    {
        QJsonObject dataObj = dataVal.toObject();
        int uId = dataObj.value("id").toInt();
        qDebug() << "ParseFriendMessageReply: "<< uId << ", " << dataVal;
    }
}

/**
 * @brief AutoClient::GetHeadPixmap
 * @param name
 * @return
 */
QString AutoClient::GetHeadPixmap(const QString &name) const
{
    if (QFile::exists(Config::m_strHeadPath + name)) {
        return Config::m_strHeadPath + name;
    }

    return ":/resource/head/1.bmp";
}

/**
 * @brief AutoClient::ParseUpFriendHead
 * 更新好友头像
 * @param dataVal
 */
void AutoClient::ParseUpFriendHead(const QJsonValue &dataVal)
{
    if (!dataVal.isObject()) return;
    QJsonObject jsonObj = dataVal.toObject();
    int nId = jsonObj.value("id").toInt();
    QString strHead = jsonObj.value("head").toString();

    DownloadFriendHead(nId, strHead);
}

/**
 * @brief AutoClient::DownloadFriendHead
 * 到服务器下载用户头像
 * @param strHead
 */
void AutoClient::DownloadFriendHead(const int &userId, const QString &strHead)
{
    if (QFile::exists(strHead)) return;

    QJsonObject jsonReply;
    jsonReply.insert("from", m_msgSocket->m_localUser.m_id);
    jsonReply.insert("id",  -2);
    jsonReply.insert("msg", strHead);

    m_msgSocket->SltSendMessage(GetFile, jsonReply);
    qDebug() << "get file" << jsonReply;
}
